import Card from '@/components/Card';
import Description from '@/components/Description';
import { ProForm, ProFormItem, ProFormSelect } from '@/components/Pro';
import {
  clusterEnergyIndex,
  clusterReliabilityMetrics,
  clusterTechnicalIndex,
  electIndex,
  energyIndex,
  reliabilityMetrics,
} from '@/pages/Forecast/PanoramicAnalysis/descriptions';
import { deviceControllerGetDeviceLevelInfo as getBmuList } from '@/services/ess/deviceInfo';
import { panoramaControllerGetPanorama as getDecriptions } from '@/services/ess/diagnosisPanorama';
import { useIntl } from '@umijs/max';
import { DatePicker, Radio, RadioChangeEvent, Space } from 'antd';
import dayjs, { Dayjs } from 'dayjs';
import React, { useEffect, useRef, useState } from 'react';
//
// interface Option {
//   value: string | number;
//   label: string;
//   children?: Option[];
// }

// function getFirstValues(targetList: Option[]) {
//   const resultArr: string[] = [];
//
//   function findFirstChild(arr: Option[]) {
//     arr.forEach((item: Option, index: number) => {
//       if (index === 0) {
//         resultArr.push(item.code);
//         if (Array.isArray(item.children) && item.children.length) {
//           findFirstChild(item.children);
//         }
//       }
//     });
//   }
//
//   findFirstChild(targetList);
//   return resultArr;
// }

const Index: React.FC = () => {
  const intl = useIntl();

  const [currentCycle, setCurrentCycle] = useState('MONTH');
  const [currentDate, setCurrentDate] = useState(dayjs().subtract(1, 'month'));

  const formRef = useRef(null);
  const [bmsList, setBmsList] = useState([]);
  const [currentStack, setCurrentStack] = useState<string>();
  // 整站描述
  const [stationDescription, setStationDescription] = useState({
    energy: electIndex,
    efficiency: energyIndex,
    reliability: reliabilityMetrics,
  });
  // 电池堆描述
  const [stackDescription, setStackDescription] = useState({
    energy: clusterTechnicalIndex,
    efficiency: clusterEnergyIndex,
    reliability: clusterReliabilityMetrics,
  });
  // const [bmsValue, setBmsValue] = useState<string[]>([]);
  // const [stationStatusItems, setStationStatusItems] = useState([
  //   {
  //     key: 'soc',
  //     label: 'SOC(%)',
  //     children: '',
  //   },
  //   {
  //     key: 'soh',
  //     label: 'SOH(%)',
  //     children: '',
  //   },
  //   {
  //     key: 'equivalentDischargeTimes',
  //     label: intl.formatMessage({ id: 'diagnosticPrediction.analysis.cycles' }),
  //     children: '',
  //   },
  //   {
  //     key: 'countOfCycle',
  //     label: intl.formatMessage({ id: 'diagnosticPrediction.analysis.cycleIndex' }),
  //     children: '',
  //   },
  //   {
  //     key: 'countOfLifeCycle',
  //     label: intl.formatMessage({ id: 'diagnosticPrediction.analysis.chargeDischargeLife' }),
  //     children: '',
  //   },
  //   {
  //     key: 'efficiencyOfChargeAndDischarge',
  //     label: `${intl.formatMessage({
  //       id: 'diagnosticPrediction.analysis.chargeDischargeEfficiency',
  //     })}(%)`,
  //     children: '',
  //     span: 1,
  //   },
  // ]);

  // const [bmuStatusItems, setBmuStatusItems] = useState([
  //   {
  //     key: 'usedCapacity',
  //     label: `${intl.formatMessage({
  //       id: 'diagnosticPrediction.analysis.availableCapacityEnergy',
  //     })}(Ah/kWh)`,
  //     children: '',
  //   },
  //   {
  //     key: 'continuousWorkingTime',
  //     label: intl.formatMessage({ id: 'diagnosticPrediction.analysis.sustainableWorkingHours' }),
  //     children: '',
  //   },
  //   {
  //     key: 'countOfCycle',
  //     label: intl.formatMessage({ id: 'diagnosticPrediction.analysis.recyclableLife' }),
  //     children: '',
  //   },
  //   {
  //     key: 'maxChargeEfficiency',
  //     label: `${intl.formatMessage({
  //       id: 'diagnosticPrediction.analysis.maximumChargingEfficiency',
  //     })}(%)`,
  //     children: '',
  //   },
  //   {
  //     key: 'maxDischargeEfficiency',
  //     label: `${intl.formatMessage({
  //       id: 'diagnosticPrediction.analysis.maximumDischargeEfficiency',
  //     })}(%)`,
  //     children: '',
  //     span: 1,
  //   },
  // ]);

  // const bmsChange = (value: string[]) => {
  //   setBmsValue(value);
  //   if (!Array.isArray(value) || !value.length) {
  //     return;
  //   }
  //   getBmuStatus({
  //     stationId,
  //     bmsCode: value[value.length - 1],
  //   }).then((res) => {
  //     const data = res.data || {};
  //     const result = [...bmuStatusItems].map((item) => {
  //       if (item.key === 'usedCapacity' || item.key === 'usedEnergy') {
  //         const valueStr1 = data.usedCapacity;
  //         const valueStr2 = data.usedEnergy;
  //         if (
  //           (valueStr1 === undefined || valueStr1 === null) &&
  //           (valueStr2 === undefined || valueStr2 === null)
  //         ) {
  //           item.children = '--';
  //         } else {
  //           item.children = (valueStr1 ?? '--') + '/' + (valueStr2 ?? '--');
  //         }
  //       } else {
  //         item.children = data[item.key];
  //       }
  //       return item;
  //     });
  //     setBmuStatusItems(result);
  //   });
  // };
  useEffect(() => {
    // getStationStatus().then((res) => {
    //   const data = res.data || {};
    //   const result = [...stationStatusItems].map((item) => {
    //     if (
    //       item.key === 'equivalentDischargeTimes' &&
    //       data[item.key] !== undefined &&
    //       data[item.key] !== null
    //     ) {
    //       item.children = parseFloat(`${data[item.key]}`).toFixed(2);
    //     } else {
    //       item.children = data[item.key];
    //     }
    //     return item;
    //   });
    //   setStationStatusItems(result);
    // });

    getBmuList({}).then((res: API.ApiResultDeviceLevelInfo) => {
      // const combinedTree: API.DeviceInfo[] = [
      //   ...(res?.data?.deviceBoxInfos ?? []),
      //   ...(res?.data?.deviceBmsInfos ?? []),
      // ];
      // const nodeMapping = {};
      // for (const node of combinedTree) {
      //   node.children = [];
      //   nodeMapping[node.id] = node;
      // }
      // const tree: API.DeviceInfo[] = [];
      // combinedTree.forEach((node) => {
      //   if (node.parentId === 0) {
      //     tree.push(node);
      //   } else if (nodeMapping[node.parentId]) {
      //     nodeMapping[node.parentId].children.push(node);
      //   }
      // });
      if (res.success) {
        setBmsList(res.data.deviceBmsInfos);
        setCurrentStack(res.data.deviceBmsInfos[0]?.code);
      }
      // const value = getFirstValues(tree);
      // bmsChange(value);
    });
  }, []);
  const [radioValue, setRadioValue] = useState(0);
  const cycleList = [
    {
      label: intl.formatMessage({ id: 'global.month' }),
      value: 'MONTH',
    },
    {
      label: intl.formatMessage({ id: 'batteryVoltage.safe.quarter' }),
      value: 'QUARTER',
    },
    {
      label: intl.formatMessage({ id: 'global.year' }),
      value: 'YEAR',
    },
  ];
  const onChangeRadio = (e: RadioChangeEvent) => {
    setRadioValue(e.target.value);
    formRef?.current?.submit();
  };
  /**
   * 获得描述列表
   * @param obj
   */
  const getDescriptionText = (obj: API.PanoramaDataVO) => {
    if (radioValue === 0) {
      setStationDescription({
        energy: electIndex.map((item) => {
          return {
            ...item,
            children: obj.energy[item.key],
          };
        }),
        efficiency: energyIndex.map((item) => {
          return {
            ...item,
            children: obj.efficiency[item.key],
          };
        }),
        reliability: reliabilityMetrics.map((item) => {
          return {
            ...item,
            children: obj.reliability[item.key],
          };
        }),
      });
    } else {
      setStackDescription({
        energy: clusterTechnicalIndex.map((item) => {
          return {
            ...item,
            children: obj.energy[item.key],
          };
        }),
        efficiency: clusterEnergyIndex.map((item) => {
          return {
            ...item,
            children: obj.efficiency[item.key],
          };
        }),
        reliability: clusterReliabilityMetrics.map((item) => {
          return {
            ...item,
            children: obj.reliability[item.key],
          };
        }),
      });
    }
  };
  /**
   * 格式化日期
   * @param val
   */
  const getDateFormat = (val: Dayjs | string) => {
    /**
     * 获得对应的季度
     * @param dateString
     */
    function getQuarter(dateString: string | Dayjs): string {
      const quarter = dayjs(dateString).quarter();
      const year = dayjs(dateString).year();
      return `${year}-Q${quarter}`;
    }

    return currentCycle === 'MONTH'
      ? dayjs(val).format('YYYY-MM')
      : currentCycle === 'QUARTER'
      ? getQuarter(val)
      : dayjs(val).format('YYYY');
  };
  useEffect(() => {
    formRef?.current?.submit();
  }, []);
  return (
    <div
      style={{
        display: 'flex',
        flexWrap: 'wrap',
        gap: 20,
        flexDirection: 'column',
      }}
    >
      <Card
        title={
          <div>
            <div>
              <span style={{ marginRight: '24px' }}>
                {intl.formatMessage({ id: 'diagnosticPrediction.analysis.panoramic' })}
              </span>
              <Radio.Group onChange={onChangeRadio} value={radioValue}>
                <Radio value={0}>{intl.formatMessage({ id: 'global.plant' })}</Radio>
                <Radio value={1}>{intl.formatMessage({ id: 'batteryVoltage.safe.stack' })}</Radio>
              </Radio.Group>
            </div>
          </div>
        }
        styles={{
          body: {
            width: '100%',
          },
        }}
        hasHeaderBorder={true}
      >
        <ProForm
          params={{
            cycle: currentCycle,
            radioValue: radioValue,
          }}
          layout={'inline'}
          formRef={formRef}
          onReset={() => {
            setCurrentCycle('MONTH');
            setCurrentDate(dayjs().subtract(1, 'month'));
            setCurrentStack(bmsList[0].code);
            formRef?.current.submit();
          }}
          submitter={{
            searchConfig: {
              submitText: intl.formatMessage({ id: 'statistics.income.search' }),
              resetText: intl.formatMessage({ id: 'statistics.income.reset' }),
            },
            render: (props, dom) => [...dom],
          }}
          onFinish={async (values) => {
            const params = {
              deviceType: radioValue === 0 ? 'STATION' : 'BMS',
              cycleType: values.cycle,
              date: getDateFormat(values?.date),
              code: radioValue === 1 ? currentStack : undefined,
            };
            const res = await getDecriptions(params);
            getDescriptionText(res.data);
          }}
        >
          <ProFormSelect
            label={intl.formatMessage({ id: 'forecast.analysisCycles' })}
            name={'cycle'}
            allowClear={false}
            initialValue={'MONTH'}
            options={cycleList}
            style={{ width: 120 }}
            onChange={(e) => {
              setCurrentCycle(e);
            }}
          ></ProFormSelect>
          <ProFormItem
            label={intl.formatMessage({ id: 'statistics.common.period' })}
            name={'date'}
            initialValue={dayjs().subtract(1, 'month')}
          >
            <DatePicker
              value={currentDate}
              picker={currentCycle.toLowerCase()}
              onChange={(e) => {
                setCurrentDate(e);
              }}
            ></DatePicker>
          </ProFormItem>
          {radioValue === 1 && (
            <ProFormSelect
              allowClear={false}
              label={intl.formatMessage({ id: 'batteryVoltage.safe.stack' })}
              name={'stack'}
              fieldProps={{
                options: bmsList,
                value: currentStack,
                fieldNames: {
                  label: 'name',
                  value: 'code',
                },
                onChange: (e: string) => {
                  setCurrentStack(e);
                },
              }}
            ></ProFormSelect>
          )}
        </ProForm>
      </Card>
      {/*<Card*/}
      {/*  title={intl.formatMessage({ id: 'diagnosticPrediction.analysis.plantStatusAssessment' })}*/}
      {/*>*/}
      {/*  <Description items={stationStatusItems} labelStyle={{ textAlign: 'right' }} />*/}
      {/*</Card>*/}
      {/*<ConfigProvider*/}
      {/*  theme={{*/}
      {/*    components: {*/}
      {/*      Card: {*/}
      {/*        headerHeight: 90,*/}
      {/*      },*/}
      {/*    },*/}
      {/*  }}*/}
      {/*>*/}
      {/*<Card*/}
      {/*  title={intl.formatMessage({*/}
      {/*    id: 'diagnosticPrediction.analysis.batteryStatusAssessment',*/}
      {/*  })}*/}
      {/*  // extra={*/}
      {/*  //   <Cascader*/}
      {/*  //     value={bmsValue}*/}
      {/*  //     onChange={bmsChange}*/}
      {/*  //     placeholder={intl.formatMessage({*/}
      {/*  //       id: 'diagnosticPrediction.diagnosis.batterySelect',*/}
      {/*  //     })}*/}
      {/*  //     style={{ minWidth: 180 }}*/}
      {/*  //     options={bmsList}*/}
      {/*  //     fieldNames={{*/}
      {/*  //       label: 'name',*/}
      {/*  //       value: 'code',*/}
      {/*  //       children: 'children',*/}
      {/*  //     }}*/}
      {/*  //   />*/}
      {/*  // }*/}
      {/*>*/}
      {/*  /!*<div style={{ marginBlockEnd: 15 }}>*!/*/}
      {/*  /!*  <Description items={bmuStatusItems} labelStyle={{ textAlign: 'right' }} />*!/*/}
      {/*  /!*</div>*!/*/}
      {/*</Card>*/}
      {/*</ConfigProvider>*/}
      {radioValue === 0 && (
        <Space direction={'vertical'}>
          <Card title={intl.formatMessage({ id: 'device.electricalIndicators' })}>
            <Description items={stationDescription.energy}></Description>
          </Card>
          <Card title={intl.formatMessage({ id: 'device.energyEfficiencyIndicators' })}>
            <Description items={stationDescription.efficiency}></Description>
          </Card>
          <Card title={intl.formatMessage({ id: 'device.reliabilityIndicators' })}>
            <Description items={stationDescription.reliability}></Description>
          </Card>
        </Space>
      )}
      {radioValue === 1 && (
        <Space direction={'vertical'}>
          <Card title={intl.formatMessage({ id: 'device.technicalIndicators' })}>
            <Description items={stackDescription.energy}></Description>
          </Card>
          <Card title={intl.formatMessage({ id: 'device.energyEfficiencyIndicators' })}>
            <Description items={stackDescription.efficiency}></Description>
          </Card>
          <Card title={intl.formatMessage({ id: 'device.reliabilityIndicators' })}>
            <Description items={stackDescription.reliability}></Description>
          </Card>
        </Space>
      )}
    </div>
  );
};

export default Index;
